﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;

namespace _5_NovaAdmin.Infrastructure.Persistence.Context;

public static class EFExtension
{
    /// <summary>
    /// 执行迁移
    /// </summary>
    /// <param name="app"></param>
    public static void MigrationDatabase(this IApplicationBuilder app)
    {
        using var scope = app.ApplicationServices.CreateScope();

        var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        context.Database.EnsureCreated(); // 自动创建 CAP 表结构  第一次数据库没创建的时候,会自动创建数据库和表结构
        //context.Database.Migrate();//执行迁移
        context.AddSeed();
    }

    /// <summary>
    ///  添加种子数据
    /// </summary>
    /// <param name="app"></param>
    public static void AddSeed(this AppDbContext context)
    {
        // 如果 User 表为空，插入种子数据
        if (!context.User.Any())
        {
            User user = new User() { UserName = "王琪", Password = "", Email = "" };
            user.ChangeCreationAudit(new CreationAuditInfo<Guid>(Guid.NewGuid(), "", DateTime.Now));
            context.User.Add(user);
            context.SaveChanges();
        }
    }
}

